﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace GenCallDB
{
	public class LicenseDetails
	{
		public string RosterId
		{
			get;
			private set;
		}

		public string Name
		{
			get;
			private set;
		}

		public string Location
		{
			get;
			private set;
		}

		public bool IsLocal
		{
			get;
			private set;
		}

		public string LocationSqlValue
		{
			get
			{
				if ( string.IsNullOrWhiteSpace( Location ) )
					return "NULL";
				else
					return string.Format( "'{0}'", Location );
			}
		}

		public LicenseDetails( string[] values, bool isLocal )
		{
			RosterId = values[ Program.CallsignIndex ];
			Name = values[ Program.NameIndex ];
			Location = values[ Program.LocationIndex ];
			IsLocal = isLocal;
		}

		public LicenseDetails( string values )
		{
			string[]
				splitValues = values.Split( '\t' );

			RosterId = splitValues[ 0 ];
			Name = splitValues[ 1 ];
			Location = splitValues[ 2 ];
			IsLocal = bool.Parse( splitValues[ 3 ] );
		}

		public override string ToString()
		{
			return string.Format( "{0}\t{1}\t{2}\t{3}", RosterId, Name, Location ?? string.Empty, IsLocal );
		}

		public override bool Equals( object obj )
		{
			LicenseDetails
				other = ( LicenseDetails ) obj;

			return RosterId == other.RosterId && Name == other.Name && LocationSqlValue == other.LocationSqlValue && IsLocal == other.IsLocal;
		}

		public void WriteInsertSql( StreamWriter writer )
		{
			writer.WriteLine( "INSERT INTO valid_callsigns ( roster_id, name, location, is_local ) VALUES ( '{0}', '{1}', {2}, {3} );",
				RosterId, Name, LocationSqlValue, IsLocal ? 1 : 0 );
		}

		public void WriteUpdateSql( StreamWriter writer )
		{
			writer.WriteLine( "UPDATE valid_callsigns SET name = '{1}', location = {2}, is_local = {3} WHERE roster_id = '{0}';",
				RosterId, Name, LocationSqlValue, IsLocal ? 1 : 0 );
		}

		public void WriteDeleteSql( StreamWriter writer )
		{
			writer.WriteLine( "DELETE FROM valid_callsigns WHERE roster_id = '{0}';", RosterId );
		}
	}
}
